// src/mock/modules/user.js
import Mock from 'mockjs';
import { ROLE_PERMISSIONS } from '@/mock/authData.js'

// 创建内存数据库
export const mockDatabase = (() => {
    // 生成用户数据
    const generateUsers = Mock.mock({
        'list|20-50': [
            {
                'id|+1': 1,
                'username': '@word(5,10)', // 添加用户名字段
                'name': '@cname',
                'email': '@email',
                'phone': /1[3-9]\d{9}/,
                'role': '@pick(["admin", "public", "lawyer"])', // 添加角色字段
                'createdAt': '@datetime',
                'avatar': '@image("100x100")',
                'status|0-2': 0, // 0-正常, 1-禁用, 2-未激活
                'password': '123456' // 添加默认密码字段
            }
        ]
    }).list;
    // 添加固定管理员账号
    const fixedAdminUser = {
        id: 0,
        username: 'ad',
        name: '系统管理员',
        email: 'admin@legal-aid.com',
        phone: '13800000000',
        role: 'admin',
        createdAt: new Date().toISOString(),
        avatar: '',
        status: 0,
        password: '1' // 管理员默认密码
    };

    return {
        users: [fixedAdminUser, ...generateUsers], // 将管理员放在第一位
        currentUser: null
    };
})();

/**
 * 用户模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
    console.log(mockDatabase.users);

    // 获取用户列表（带分页）
    mock.onGet('/users').reply(config => {
        const { page = 1, size = 10 } = config.params;
        const start = (page - 1) * size;
        const end = start + size;
        const paginated = mockDatabase.users.slice(start, end);

        return [200, {
            code: 200,
            data: paginated,
            pagination: {
                page,
                size,
                total: mockDatabase.users.length,
                totalPages: Math.ceil(mockDatabase.users.length / size)
            }
        }];
    });

    // 获取单个用户
    mock.onGet(/\/users\/\d+$/).reply(config => {
        const userId = config.url.split('/').pop();
        const user = mockDatabase.users.find(u => u.id == userId);

        return user
            ? [200, { code: 200, data: user }]
            : [404, { code: 404, message: '用户不存在' }];
    });

    // 创建用户
    mock.onPost('/users').reply(config => {
        const newUser = JSON.parse(config.data);
        newUser.id = Math.max(...mockDatabase.users.map(u => u.id)) + 1;
        newUser.createdAt = new Date().toISOString();
        newUser.status = 2; // 新用户默认未激活

        mockDatabase.users.unshift(newUser);

        return [201, {
            code: 201,
            message: '用户创建成功',
            data: newUser
        }];
    });

    // 用户登录
    mock.onPost('/api/login').reply(config => {
        const { username, password } = JSON.parse(config.data);
        const user = mockDatabase.users.find(u =>
            u.username === username || u.phone === username
        );

        // 模拟登录失败场景
        if (!user) return [401, { code: 401, message: '用户不存在' }];
        if (user.status !== 0) return [403, {
            code: 403,
            message: user.status === 1 ? '账户已禁用' : '账户未激活，请验证邮箱'
        }];
        if (user.password !== password) return [401, { code: 401, message: '密码错误' }];

        // 更新当前用户
        mockDatabase.currentUser = user;

        return [200, {
            code: 200,
            message: '登录成功',
            data: {
                token: `mock_jwt_token_${Date.now()}`,
                expires: 3600 * 24 * 7, // 7天有效期
                user
            }
        }];
    });

    // 获取当前用户
    mock.onGet('/currentUser').reply(() => {
        return mockDatabase.currentUser
            ? [200, { code: 200, data: mockDatabase.currentUser }]
            : [401, { code: 401, message: '未登录' }];
    });

    // 用户注册-公众
    mock.onPost('/user/register/public').reply(config => {
        const data = JSON.parse(config.data);
        const { username, phone } = data;

        // 检查用户名和手机号是否重复
        const usernameExists = mockDatabase.users.some(u => u.username === username);
        const phoneExists = mockDatabase.users.some(u => u.phone === phone);

        if (usernameExists) return [400, { code: 400, message: '用户名已存在' }];
        if (phoneExists) return [400, { code: 400, message: '手机号已注册' }];

        const newUser = {
            id: mockDatabase.users.length + 1,
            username,
            phone,
            ...data,
            role: 'public', // 明确角色类型
            createdAt: new Date().toISOString(),
            status: 0
        };

        mockDatabase.users.push(newUser);
        return [200, { code: 200, message: '注册成功' }];
    });

    // 用户注册 - 律师用户
    mock.onPost('/user/register/lawyer').reply(config => {
        const data = JSON.parse(config.data);
        const { username, phone } = data;

        // 检查用户名和手机号是否重复
        const usernameExists = mockDatabase.users.some(u => u.username === username);
        const phoneExists = mockDatabase.users.some(u => u.phone === phone);

        if (usernameExists) return [400, { code: 400, message: '用户名已存在' }];
        if (phoneExists) return [400, { code: 400, message: '手机号已注册' }];

        // 创建新律师用户
        const newUser = {
            id: mockDatabase.users.length + 1,
            ...data,
            role: 'lawyer', // 明确角色类型
            createdAt: new Date().toISOString(),
            status: 0
        };

        mockDatabase.users.push(newUser);
        return [200, { code: 200, message: '注册成功' }];
    });
}